<template>
  <div class="xiaobu-container" v-closeSelect="'window'">
    <el-form
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      class="search-form clearfix"
    >
      <el-form-item class="search-field fl" label="字典名称" prop="dictName">
        <el-input
          v-model.trim="queryParams.dictName"
          placeholder="请输入字典名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item class="search-field fl" label="字典代码" prop="dictCode">
        <el-input
          v-model.trim="queryParams.dictCode"
          placeholder="请输入字典代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item class="search-field fl" label="状态" prop="status">
        <el-select-dict
          dictType="STATUS"
          clearable
          placeholder="请选择状态"
          v-model="queryParams.status"
          @dictChange="handleQuery"
        ></el-select-dict>
      </el-form-item>
      <el-form-item class="search-field fl" label="创建时间" prop="beginTime">
        <el-date-picker
          v-model="dateRange"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          @change="handleQuery"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item class="fr">
        <el-button plain @click="resetQuery">重 置</el-button>
        <el-button type="primary" @click="handleQuery">查 询</el-button>
      </el-form-item>
    </el-form>
    <div class="table-wrap">
      <div class="table-control-box">
        <el-button
          v-hasPermi="['system:dict:create']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
        <el-button
          v-hasPermi="['system:dict:update']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >编辑</el-button
        >
        <el-button
          v-hasPermi="['system:dict:delete']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
          >删除</el-button
        >
      </div>
      <div class="table-box">
        <el-table
          ref="dictTable"
          :class="{'empty': list.length === 0}" 
          empty-text=" "
          v-loading="loading"
          :data="list"
          row-key="dictId"
          @selection-change="handleSelectionChange"
          @row-click="clickRow"
        >
          <el-table-column
            :selectable="checkSelectable"
            :reserve-selection="true"
            type="selection"
            width="55"
            align="center"
          />
          <el-table-column
            label="字典代码"
            prop="dictCode"
            align="center"
            min-width="200px"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                @click.native.stop="
                  $router.push({
                    name: 'systemDictItemManage',
                    query: { dictId: scope.row.dictId },
                  })
                "
                >{{ scope.row.dictCode }}</el-link
              >
            </template>
          </el-table-column>
          <el-table-column
            label="字典名称"
            prop="dictName"
            align="center"
            min-width="200px"
          />
          <el-table-column-dict
            dictType="STATUS"
            dictTypeNode="tag"
            label="状态"
            align="center"
            prop="status"
            min-width="100px"
          ></el-table-column-dict>
          <el-table-column-dict
            dictType="YES_NO"
            label="是否系统预设"
            align="center"
            prop="isSystem"
            min-width="120px"
          ></el-table-column-dict>
          <el-table-column-dict
            dateFormat="datetime"
            label="创建时间"
            align="center"
            prop="createTime"
            min-width="168px"
          ></el-table-column-dict>
          <el-table-column-dict
            dateFormat="datetime"
            defaultVal="--"
            label="最后更新时间"
            align="center"
            prop="updateTime"
            min-width="168px"
          ></el-table-column-dict>
          <el-table-column
            v-if="
              hasPermi([
                'system:dict:status',
                'system:dict:read',
                'system:dict:delete',
              ])
            "
            label="操作"
            align="center"
            width="256px"
            fixed="right"
            class-name="small-padding "
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['system:dict:status']"
                :disabled="scope.row.isSystem === '1'"
                size="mini"
                :type="scope.row.status === '1' ? 'warning' : 'success'"
                @click.native.stop="handleStatusChange(scope.row)"
                >{{ scope.row.status === "1" ? "停用" : "启用" }}</el-button
              >
              <el-button
                v-hasPermi="['system:dict:read']"
                size="mini"
                type="primary"
                icon="el-icon-view"
                @click.native.stop="handleUpdate(scope.row)"
                >查看</el-button
              >
              <el-button
                v-hasPermi="['system:dict:delete']"
                :disabled="scope.row.isSystem === '1'"
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click.native.stop="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 添加或编辑对话框 -->
    <dict-dialog
      ref="dictDialog"
      :title="baseForm.dictId ? (isUpdate ? '编辑字典' : '查看字典') : '新增字典'"
      :visible.sync="open"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :isUpdate="isUpdate"
      :baseForm="baseForm"
      @close="open = false"
      @successs="getList"
      width="1024px"></dict-dialog>
  </div>
</template>

<script>
import dictDialog from "./components/dict-dialog.vue"
import { dictApi } from "@/api"
export default {
  name: "systemDictManage",
  components: {
    dictDialog
  },
  data() {
    return {
      isUpdate: false, // 是否是编辑
      //搜索条件参数
      queryParams: {
        dictName: "", //字典名称
        dictCode: "", //字典代码
        status: "", // 字典项状态
        beginTime: "",
        endTime: "",
        pageNum: 1,
        pageSize: 10
      },
      dateRange: [],
      list: [],
      selection: [], //选中的项
      loading: false,
      total: 0,

      // 非单个禁用
      single: true,
      // 非多个禁用(0个禁用)
      multiple: true,

      open: false,
      // 表单参数
      baseForm: {
        dictName: "", //字典名称
        dictCode: "", //字典代码
        remark: "" // 备注
      }
    }
  },
  watch: {
    open(val) {
      if (!val) {
        this.isUpdate = false
        this.baseForm = {
          dictName: "", //字典名称
          dictCode: "", //字典代码
          remark: "" // 备注
        }
        this.$refs.dictDialog&&this.$refs.dictDialog.resetForm()
      }
    }
  },
  created() {
    //获取列表
    this.getList()
  },
  methods: {
    // 系统内设用户 禁止操作
    checkSelectable(row, index) {
      if (row.isSystem === "1") {
        return false
      } else {
        return true
      }
    },
    //点击行
    clickRow(row) {
      //系统预设用户 不做处理
      if (row.isSystem === "1") {
        return
      }
      this.$refs.dictTable.toggleRowSelection(row)
    },
    //批量删除用户
    handleBatchDelete() {
      let str = ""
      const ids = []
      for (let i = 0; i < this.selection.length; i++) {
        const item = this.selection[i]
        ids.push(item.dictId)
        str += item.dictName
        if (i !== this.selection.length - 1) {
          str += ", "
        }
      }

      this.$modal
        .confirm('是否确认删除字典项为"【' + str + '】"的数据项？')
        .then(function() {
          return dictApi.batchDeleteItems({ ids })
        })
        .then(() => {
          this.handleQuery()
          this.$modal.msgSuccess("批量删除字典成功")
        })
        .catch(() => {})
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 清空已选项
      this.$refs.dictTable.clearSelection()
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true
      dictApi
        .getList(this.addDateRange(this.queryParams, this.dateRange))
        .then((response) => {
          this.list = response.rows
          this.total = response.total
          this.loading = false
        })
        .catch((err) => {
          if (err?.name === "CanceledError") {
            return
          }
          this.loading = false
        })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
    },

    /** 编辑按钮操作 */
    handleUpdate(row) {
      if (!row.dictId) {
        this.isUpdate = true
      }
      const id = row.dictId || (this.selection[0] && this.selection[0].dictId)
      dictApi.getDetailById({ id }).then((data) => {
        this.baseForm = Object.assign(this.baseForm, data)
        this.open = true
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.dictId
      this.$modal
        .confirm('是否确认删除字典为"' + row.dictName + '"的数据项？')
        .then(function() {
          return dictApi.deleteItem({ id })
        })
        .then(() => {
          this.handleQuery()
          // 判断删除的项是否被勾选了
          const flag = this.selection.find((item) => item.dictId === id)
          flag && this.$refs.dictTable.toggleRowSelection(row, false)
          this.$modal.msgSuccess("删除成功")
        })
    },
    // 状态改变事件
    handleStatusChange(row) {
      dictApi
        .changeStatus({
          dictId: row.dictId,
          status: row.status === "1" ? "0" : "1"
        })
        .then((data) => {
          this.$modal.msgSuccess("改变状态成功")
          this.getList()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.xiaobu-container {
  .tips {
    font-size: 24px;
    margin-left: 12px;
    color: $mainColor;
  }
}
</style>
